package org.terramagnet.pdmviewer.web;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.annotation.Resource;
import org.dom4j.DocumentException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.terramagnet.pdmviewer.parser.PDM;
import org.terramagnet.pdmviewer.parser.Parser;

@Controller
public class HomeController {

    Parser parser = new Parser();
    @Resource
    private FileStore fileStore;

    @RequestMapping("/")
    public String root() throws IOException {
        return "index";
    }

    @RequestMapping("/ajax/checksum/{checksum}")
    @ResponseBody
    public boolean ajaxFileByChecksum(@PathVariable String checksum) {
        File f = fileStore.get(checksum);
        return f != null;
    }

    @RequestMapping(value = "/upfile", method = RequestMethod.POST)
    public String upfile(@RequestParam("upfile") MultipartFile file) throws IOException {
        String checksum = fileStore.save(file);
        return "redirect:/pdm/" + checksum;
    }

    @RequestMapping("/view/{checksum}")
    public String view(@PathVariable String checksum,Model ui) throws FileNotFoundException, DocumentException {
        File file = fileStore.get(checksum);
        PDM pdm = parser.parsePdm(file);
        ui.addAttribute("pdm", pdm);
        return "view";
    }
}
